from flask import render_template, redirect, url_for, flash
import datetime
from simple_blog import app, db
from simple_blog.models import Post
from simple_blog.forms import NewPostForm, EditPostForm


@app.route('/')
def index():
    posts = Post.query.all()
    return render_template('index.html', posts=posts)


@app.route('/posts/new', methods=['GET', 'POST'])
def new_post():
    form = NewPostForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        if not Post.query.filter_by(title=title).first():
           post = Post(title=title, body=body)
           db.session.add(post)
           db.session.commit()
        #    flash('博客发表成功!')
           return redirect(url_for('index'))
        else:
            flash('博客标题已存在,请重命名标题!')
    return render_template('new_post.html', form=form)


@app.route('/posts/<int:post_id>')
def get_post(post_id):
    post = Post.query.filter_by(id=post_id).first()
    print(post)
    if post:
        return render_template('get_post.html', post=post)
    else:
        pass
        # 404, not found

# 数据删除一般使用POST请求
@app.route('/delete/<int:post_id>', methods=['POST'])
def delete_post(post_id):
    post = Post.query.filter_by(id=post_id).first()
    db.session.delete(post)
    db.session.commit()
    flash(f'文章已经删除, title={post.title}')
    return redirect(url_for('index'))


@app.route('/posts/<int:post_id>/edit', methods=['GET', 'POST'])
def edit_post(post_id):
    post = Post.query.filter_by(id=post_id).first()
    def check_valid(post_):
        if not post_.title:
            flash('post标题不能为空')
            return False
        elif not post_.body:
            flash('post内容不能为空')
            return False
        return True
    
    form = EditPostForm()
    if form.validate_on_submit():
        if check_valid(post):
            new_title = form.title.data
            new_body = form.body.data
            if new_title and new_body:
                post.title = new_title
                post.body = new_body
                db.session.commit()
                flash('编辑修改成功!')
                return redirect(url_for('index'))
    return render_template('edit_post.html', form=form, post=post)

            




